axios = require('axios')
send = require('srv/smtp')
PG = require('db/pg')
CAPTCHA = require 'config/captcha'
{CACHE} = require('db/redis')
b64id = require 'util/b64id'

RE_MAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

module.exports = new require('koa-router')().get({

"mail/:key":(ctx)->
    {key} = ctx.params
    ctx.body = (await CACHE.get("auth/new/mail/"+key)) or ''

"captcha/id":(ctx)->
    ctx.body = CAPTCHA.ID

}).post({

"new/mail" : (ctx)->
    {mail, ticket, appid, randstr, host} = ctx.request.body
    mail = mail.toLowerCase()
    if mail.length > 250
        raise val:3 # 邮件地址太长了

    if RE_MAIL.test(mail)
        PG.transaction (trx) ->
            mail_id = await trx.select_val_id('auth.mail', mail)
            if mail_id
                user_id = await trx.select_val_id('auth.user_mail', mail_id)
                if user_id
                    raise val:1 # 邮件已经注册


            {data} = await axios.get(
                CAPTCHA.URL
                params:{
                    aid:CAPTCHA.ID
                    AppSecretKey:CAPTCHA.SECRET
                    Ticket:ticket
                    Randstr:randstr
                    UserIP:ctx.ip
                }
            )

            if 1!=(data.response-0)
                raise captcha:1 # 验证码错误

            # mail_id = await trx.val_id('auth.mail', mail)
            # [mail_id] = await trx.insert(
            #     {val:mail}
            # ).into('auth.mail').returning('id')
            # console.log "mail_id",mail_id, mail
            key = b64id()
            await CACHE.setex("auth/new/mail/"+key, 86400, mail)

            send {
                to:mail
                from_name:host

                subject:"[#{host}] 请验证邮箱地址，完成注册"
                text:"""\
欢迎注册 #{host} !

请点击下面的链接完成注册（若链接无法点击，请复制到浏览器地址栏）。

https://#{host}/auth/-#{key}

此链接将在二十四小时后过期失效。"""
            }

            ctx.body = 0
    else
        raise val:2 # 邮箱格式不正确


})
